var iframe_url = '';

var gadget_server_host = 'http://localhost:3002';

// Holds an array of data describing the gadgets to be rendered
var gadgetData;



/*
 * Requests the metadata for the list of gadgets contained in gadgetData
 * 
 * Successful metadata request results in a call to generateGadgets which
 * will generate the gadgets for display.
 * 
 */
function requestGadgetMetaData(url, view){
	alert('requestGadgetMetaData');
	gadget_data = [
					{
						url: url, 
						container_id: 1,
						moduleId: 1 }	
  					];
	request_metadata({"country":"default",
					  "language":"default",
					  "view": view,
					  "container":"default" },
				   gadget_data,
				   function (data) {metadata_success(data);},
				   function (error) {metadata_error(error);});
}

function renderGadget(iframe_url) {
	var view_type = document.getElementById('view_type').value;
	var content = render_gadget(iframe_url);
	while (!document.getElementById(view_type + '_view')) {}
	var div = document.getElementById(view_type + '_view');
	div.innerHTML = content;
	var x = div.getElementsByTagName("script");    
	for(var i=0;i<x.length;i++) {   
		alert(x[i].text);
		eval(x[i].text);   
	}  
}

function metadata_success(data) {
	render_metadata(data);
	var metadata = eval('(' + data + ')');
	iframe_url = metadata.gadgets[0].iframeUrl;
	dijit.byId('render_btn').setDisabled(false);
}

var MAX_DUMP_DEPTH = 10;
function dumpObj(obj, name, indent, depth){
    if (depth > MAX_DUMP_DEPTH) {
        return indent + name + ": <Maximum Depth Reached>\n";
    }   
    if (typeof obj == "object") {       
        var child = null;          
        var output = indent + name + "\n";      
        indent += "\t";
        for (var item in obj) {
            try {
                child = obj[item];
            } 
            catch (e) {
                child = "<Unable to Evaluate>"; 
            }
            if (typeof child == "object") {
                output += dumpObj(child, item, indent, depth + 1);
            }
            else {
                output += indent + item + ": " + child + "\n";
            } 
        }
        return output;
    }
    else {
        return obj;
    }
}
